package com.gwt.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gwt.cloud.result.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@Component
public class MessageResponse {

    @Autowired
    private ObjectMapper objectMapper;

    public Mono<Void> result(ServerWebExchange exchange, Integer code, String message){
        ServerHttpResponse response = exchange.getResponse();
        ApiResult result = new ApiResult<>(code, message);
        // 将错误响应转换为JSON
        String jsonResponse;
        try {
            jsonResponse = objectMapper.writeValueAsString(result);
        } catch (JsonProcessingException e) {
            // 处理JSON序列化异常
            jsonResponse = "{\"status\":-1,\"message\":\"数据解析异常！\"}";
        }
        // 设置响应头和状态码
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        // 返回错误响应
        DataBuffer buffer = response.bufferFactory().wrap(jsonResponse.getBytes(StandardCharsets.UTF_8));
        return response.writeWith(Mono.just(buffer));
    }
}
